package com.tledu.ssm.core.interceptor;

import com.tledu.ssm.model.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * @author cyrus
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // hanlder就是Controller和对应method
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Object obj = handlerMethod.getBean();
        // true代表如果没有session就会创建一个session，false没有session就会返回null
        HttpSession session = request.getSession(true);
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            // 代表没有登录
            response.sendRedirect(request.getContextPath() + "/");
            // 终止后续请求
            return false;
        }
        return super.preHandle(request, response, handler);
    }
}
